package com.haiwei.poi.word.loop;

import com.haiwei.poi.word.bean.HaiweiBeanUtil;
import com.haiwei.poi.word.poi.HaiweiXWPFTableUtil;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.util.List;

/**
 * haiweiTableRowGroup 处理工具类.
 *
 * @date: 2022-06-27
 * @version: 1.0
 * @author: karry@haiwei.com
 */
public class HaiweiRowGroupUtil {
    
    /**
     * 解析row组
     * @param row
     */
    public static void handleRowGroup(HaiweiRowGroup row) {
        if(row instanceof HaiweiRowGroupBasic){
            HaiweiRowGroupBasic haiweiTableRow = (HaiweiRowGroupBasic) row;
            handleBasicRowGroup(haiweiTableRow.getTable(), haiweiTableRow.getStartIndex());
        }else if(row instanceof HaiweiRowGroupLoop){
            HaiweiRowGroupLoop loop = (HaiweiRowGroupLoop) row;
            // 获取标签
            HaiweiLoopSign loopSign = loop.getLoopSign();
            // 获取循环数量
            int collectionLen = HaiweiBeanUtil.getCollectionLen(loopSign.getPath());
            
            // 遍历处理, i 是数据下标
            for(int i = 0 ; i < collectionLen ; i++){
                Object obj = HaiweiBeanUtil.getValue(loopSign.getPath() + "." + i);
                HaiweiBeanUtil.setBean(obj,loopSign.getItem());
                List<HaiweiRowGroup> loopRow = loop.getRows();
                // 遍历loop中的行并复制,j是行下标
                for(int j = 0; j < loopRow.size() ; j++){
                    handleRowGroup(loopRow.get(j));
                }
                HaiweiBeanUtil.clean(loopSign.getItem());
            }
        }
    }
    
    /**
     * 处理最基本的数据行
     * @param table
     * @param startIndex
     */
    private static void handleBasicRowGroup(XWPFTable table, int startIndex) {
        int insertIndex = table.getNumberOfRows();
        HaiweiXWPFTableUtil.addAndCopyRows(table
                , table.getRow(startIndex)
                , insertIndex
                , 1);
        HaiweiXWPFTableUtil.parse(table.getRow(insertIndex));
    }
}
